<template>
  <div class="home">
    <div class="avatar">
      <van-image
        round
        width="100px"
        height="100px"
        :src="userInfo.headimgurl"
      />
    </div>
    <van-cell-group>
      <van-cell title="昵 称" :value="userInfo.nickname" />
      <van-cell title="性 别" :value="userInfo.sex === 1 ? '女' : '男'" />
      <van-cell title="国 家" :value="userInfo.country" />
      <van-cell title="省 份" :value="userInfo.province" />
      <van-cell title="城 市" :value="userInfo.city" />
      <van-cell title="OPENID" :value="openId" />
    </van-cell-group>

    <div class="van-multi-ellipsis--l3 panel">
      USERINFO: {{ JSON.stringify(userInfo) }}
    </div>
    
    <van-space direction="vertical" fill style="margin: 0 10px;">
      <van-button size="small" type="primary" @click="getPageRedirect" block>获取微信授权</van-button>
    </van-space>

    <van-divider content-position="left">微信支付</van-divider>
    <wx-pay :openid="openId" />
  </div>
  
</template>

<script setup>

import WxPay from './Pay.vue'

import { ref, onMounted } from 'vue'
import { useRoute} from 'vue-router'
import axios from 'axios'

const route = useRoute()
onMounted(() => {
  const { code } = route.query
  if (code) {
    getOpenId(code)
  }
})
// 重定向
const getPageRedirect = async () => {
  const url = window.location.href.split('?')[0]
  const res = await axios.get(`/wechat/redirect?url=${url}`)
  location.href = res.data
}
// 获取openid
const openId = ref('')
const accessToken = ref('')
const getOpenId = async (code) => {
  const res = await axios.get(`/wechat/getOpenId?code=${code}`)
  if (res && res.data) {
    const { openid, access_token } = res.data
    openId.value = openid
    accessToken.value = access_token
    getUserInfo()
  }
}
// 获取用户信息
const userInfo = ref({})
const getUserInfo = async () => {
  const { data } = await axios.get('/wechat/getUserInfo')
  if (data) {
    userInfo.value = data.data
  }
}


</script>

<style scoped>
.home {
  /* padding: 10px; */
}
.avatar {
  padding: 20px 0;
  display: flex;
  justify-content: center;
}
.panel {
  background-color: #f6f6f6;
  margin: 10px;
  padding: 10px;
  border-radius: 10px;
  font-size: 12px;
}
</style>